import {encrypt,decrypt} from './crypto'
// 默认缓存期限为7天
const DEFAULT_CACHE_TIME = 60 * 60 * 24 * 7;

/**
  * 本地缓存类
  * @class LocalCache
  */
class LocalCache {
  private storage;
  constructor() {
    this.storage = localStorage;
  }
  /**
   * @description 设置缓存
   * @param key 缓存键
   * @param value 缓存值
   * @param expire 缓存时间
   */
  set(key: string, value: any, expire: number | null = DEFAULT_CACHE_TIME) {
    const stringData = JSON.stringify({
      value,
      expire: expire !== null ? new Date().getTime() + expire * 1000 : null,
    });
    this.storage.setItem(key.toUpperCase(), encrypt(stringData));
  }
  /**
   * @description 读取缓存
   * @param key 缓存键
   */
  get(key: string, def: any = null) {

    const item = this.storage.getItem(key);
    if (item) {
      const data = JSON.parse(decrypt(item));
      const value = data.value;
      const expire = data.expire;
      // 有效期内直接返回
      if (expire === null || expire >= Date.now()) {
        return value;
      } else {
        this.remove(key);
      }
    }
    return def;
  }
  /**
   * @description 从缓存删除某项
   * @param key 缓存键
   */
  remove(key: string) {
    this.storage.removeItem(key);
  }
  /**
   * @description 清空缓存
   */
  clear(): void {
    this.storage.clear();
  }
}
export const storage = new LocalCache()